﻿using DocumentFormat.OpenXml.Lite.Core.Interfaces;
using DocumentFormat.OpenXml.Lite.Core.Office;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DocumentFormat.OpenXml.Lite.Core.DocumentFS
{
    public class Directory
    {
        public string Name { get; set; }
        public Directory Parent { get; set; }

        private List<File> files = new List<File>();
        private List<Directory> directories = new List<Directory>();

        private Directory(string name)
        {
            this.Name = name;
        }

        public Directory(string name, Directory parent)
            : this(name)
        {
            this.Parent = parent;
        }

        public Directory(string name, string parent)
            : this(name)
        {
            if (parent != string.Empty)
            {
                this.Parent = DocumentFS.GetDirectory(parent);
            }
        }

        public List<File> GetFiles()
        {
            return files;
        }

        public List<File> GetFilesRecursive()
        {
            List<File> all = new List<File>();
            all.AddRange(files);
            foreach (var dir in directories)
            {
                all.AddRange(dir.GetFilesRecursive());
            }
            return all;
        }

        public List<Directory> GetDirectories()
        {
            return directories;
        }

        public File CreateFile(string name, ISerializable obj)
        {
            if (name.Contains("/"))
            {
                Directory dir = this;
                var parts = name.Split('/');
                for (int i = 0; i < parts.Length - 1; ++i)
                {
                    if (dir.ExistsDirectory(parts[i]))
                    {
                        dir = dir.GetDirectory(parts[i]);
                    }
                    else
                    {
                        dir = dir.CreateDirectory(parts[i]);
                    }
                }
                return dir.CreateFile(parts[parts.Length - 1], obj);
            }
            else
            {
                if (files.Any(f => f.Name == name))
                {
                    throw new OpenXmlException("File already exists: " + this.Parent.GetPath() + name);
                }

                File file = new File(name, this, obj);
                files.Add(file);
                return file;
            }
        }

        public Directory CreateDirectory(string name)
        {
            if (name.Contains("/"))
            {
                Directory dir = this;
                var parts = name.Split('/');
                for (int i = 0; i < parts.Length - 1; ++i)
                {
                    if (dir.ExistsDirectory(parts[i]))
                    {
                        dir = dir.GetDirectory(parts[i]);
                    }
                    else
                    {
                        dir = dir.CreateDirectory(parts[i]);
                    }
                }
                return dir.CreateDirectory(parts[parts.Length - 1]);
            }
            else
            {
                if (directories.Any(d => d.Name == name))
                {
                    throw new OpenXmlException("Directory already exists: " + this.Parent.GetPath() + name);
                }

                Directory dir = new Directory(name, this);
                directories.Add(dir);
                return dir;
            }
        }

        public bool RemoveFile(string name)
        {
            if (name.Contains("/"))
            {
                string[] path = name.Split('/');
                Directory dir = GetDirectory(string.Join(string.Empty, path.Take(path.Length - 1)));
                dir.RemoveFile(path[path.Length - 1]);
            }
            else
            {
                File file = files.FirstOrDefault(f => f.Name == name);
                if (file == null)
                {
                    return false;
                }

                files.Remove(file);
            }

            return true;
        }

        public bool RemoveDirectory(string name)
        {
            if (name.Contains("/"))
            {
                string[] path = name.Split('/');
                Directory dir = GetDirectory(string.Join(string.Empty, path.Take(path.Length - 1)));
                dir.RemoveDirectory(path[path.Length - 1]);
            }
            else
            {
                Directory dir = directories.FirstOrDefault(d => d.Name == name);
                if (dir == null)
                {
                    return false;
                }
                directories.Remove(dir);
            }

            return true;
        }

        public bool ExistsFile(string name)
        {
            if (name.Contains("/"))
            {
                Directory dir = this;
                var parts = name.Split('/');
                for (int i = 0; i < parts.Length - 1; ++i)
                {
                    if (dir.ExistsDirectory(parts[i]))
                    {
                        dir = dir.GetDirectory(parts[i]);
                    }
                    else
                    {
                        return false;
                    }
                }
                return dir.ExistsFile(parts[parts.Length - 1]);
            }
            else
            {
                return files.FirstOrDefault(f => f.Name == name) != null;
            }
        }

        public bool ExistsDirectory(string name)
        {
            if (name.Contains("/"))
            {
                Directory dir = this;
                var parts = name.Split('/');
                for (int i = 0; i < parts.Length - 1; ++i)
                {
                    if (dir.ExistsDirectory(parts[i]))
                    {
                        dir = dir.GetDirectory(parts[i]);
                    }
                    else
                    {
                        return false;
                    }
                }
                return dir.ExistsDirectory(parts[parts.Length - 1]);
            }
            else
            {
                return directories.FirstOrDefault(d => d.Name == name) != null;

            }
        }

        public File GetFile(string name)
        {
            if (name.Contains("/"))
            {
                Directory dir = this;
                var parts = name.Split('/');
                for (int i = 0; i < parts.Length - 1; ++i)
                {
                    dir = dir.GetDirectory(parts[i]);
                }
                if (!dir.ExistsFile(parts[parts.Length - 1]))
                {
                    throw new FileNotFoundException("File: " + parts[parts.Length - 1] +
                        " not found in the directory: " + dir.Name);
                }
                return dir.GetFile(parts[parts.Length - 1]);
            }
            else
            {
                File file = files.FirstOrDefault(f => f.Name == name);
                if (file == null)
                {
                    throw new FileNotFoundException("File: " + name + " not found in the directory: " + Name);
                }
                return file;
            }
        }

        public Directory GetDirectory(string name)
        {
            if (name.Contains("/"))
            {
                Directory dir = this;
                foreach (var d in name.Split('/'))
                {
                    if (!dir.ExistsDirectory(d))
                    {
                        throw new FileNotFoundException("Directory: " + d + " not found in the directory: " + dir.Name);
                    }
                    dir = dir.GetDirectory(d);
                }
                return dir;
            }
            else
            {
                Directory dir = directories.FirstOrDefault(d => d.Name == name);
                if (dir == null)
                {
                    throw new FileNotFoundException("Directory: " + name + " not found in the directory: " + Name);
                }
                return dir;
            }
        }

        public string GetPath()
        {
            Directory dir = this;
            string path = string.Empty;
            while (dir.Name != DocumentFS.Root.Name)
            {
                path = dir.Name + "/" + path;
                dir = dir.Parent;
            }
            return path = DocumentFS.Root.Name + path;
        }

        public string GetXmlPath()
        {
            return GetPath().Substring(Guid.Empty.ToString().Length + DocumentFS.Root.Name.Length + 1); ;
        }

        public static string Combine(Directory source, string relativePath)
        {
            Directory current = source;
            string[] parts = relativePath.Split('/');
            for (int i = 0; i < parts.Length - 1; ++i)
            {
                if (parts[i] == "..")
                {
                    current = current.Parent;
                }
                else
                {
                    current = current.GetDirectory(parts[i]);
                }
            }
            return current.GetXmlPath() + parts[parts.Length - 1];
        }

        public static string Combine(File target, Directory relativeTo)
        {
            string common = string.Empty;
            string pathTarget = target.GetPath();
            string relativePath = relativeTo.GetPath();
            for (int i = 0; i < relativePath.Length; ++i)
            {
                if (pathTarget[i] != relativePath[i])
                {
                    break;
                }
                common += pathTarget[i];
            }

            if (!common.EndsWith("/"))
            {
                common = common.Substring(0, common.LastIndexOf('/')) + "/";
            }

            Directory commonDir = DocumentFS.Root;
            foreach (string d in common.Split('/'))
            {
                if (d == string.Empty)
                    continue;
                commonDir = commonDir.GetDirectory(d);
            }

            string path = string.Empty;
            Directory temp = relativeTo;
            while (true)
            {
                if (temp == commonDir)
                    break;
                path += "../";
                temp = temp.Parent;
            }
            path += target.GetPath().Replace(common, "");

            return path;
        }
    }
}
